package net.code.btalk.ui;


import net.code.btalk.Buddy;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.container.MainScreen;

public class MessageScreen extends MainScreen {
	//private final BTalk btalk;
	private final Buddy buddy;
	
	private static MessageTextField msgTextField = new MessageTextField();
	private static SeparatorField separator = new SeparatorField();
	
	private static final Font[] fonts = new Font[] {Font.getDefault().derive(Font.BOLD|Font.UNDERLINED), Font.getDefault()};
	
	private static final byte[] textAttr = new byte[] {0, 1};
	
	private static int[] offsets_me = new int[] {0, "me:".length(), 0};
	private int[] offsets_buddy = new int[3];
	
	public MessageScreen(Buddy b) {
		buddy = b;
		this.setTitle("Chat with " + b.name);
		offsets_buddy[0] = 0;
		offsets_buddy[1] = b.name.length()+1;
//		this.add(msgTextField);
	}
	
	// needn't check whether this is the current buddy
	public void sendMessage(String msg) {
		this.delete(msgTextField);
		this.delete(separator);
		offsets_me[2] = offsets_me[1] + msg.length();
		this.add(new RichTextField("me:"+msg, offsets_me, textAttr, fonts, 0));
		this.add(separator);
		this.add(msgTextField);
		msgTextField.setFocus();
	}
	
	// when pushed into stack
	protected void onDisplay() {
		this.add(separator);
		this.add(msgTextField);
		msgTextField.setFocus();
	}
	
	// when popped off the stack
	protected void onUndisplay() {
		this.delete(msgTextField);
		this.delete(separator);
		buddy.btalk.currentBuddy = null;
	}
	
	public void receiveMessage(String msg, boolean current) {
		if (current) {
			this.delete(msgTextField);
			this.delete(separator);
		}
		
		offsets_buddy[2] = offsets_buddy[1] + msg.length();
		this.add(new RichTextField(buddy.name+":"+msg, offsets_buddy, textAttr, fonts, 0));
		
		if (current) {
			this.add(separator);
			this.add(msgTextField);
			msgTextField.setFocus();
		}
		
	}
	
//	public void initFields(MessageListField msgListField, TextField text) {
//		this.add(msgListField);
//		this.add(new SeparatorField());
//		this.add(text);
//		text.setFocus();
//	}
	
}
